import {useState} from 'react';
import {useUpdate} from './useUpdate';
import {getMonthEnd, getNextMonthDate, getToday} from '../lib/dayUtils';

export type DirType = 'left' |'right'

export const useCalendarDate = () => {
  const [calendarDate, setCalendarDate] = useState(window.localStorage.getItem('calendarDate') || getToday())

  useUpdate(() => {
    window.localStorage.setItem('calendarDate', calendarDate);
  }, [calendarDate]);

  const updateDate = (newDate: string) => setCalendarDate(newDate)

  const updateMonth = (direction: DirType) => {
    if (direction === 'left') {
      const prevDate = getNextMonthDate(calendarDate, -1)
      setCalendarDate(prevDate);
    } else if (direction === 'right') {
      const nextDate = getNextMonthDate(calendarDate, 1);
      if (nextDate <= getMonthEnd()) {
        setCalendarDate(nextDate);
      }
    }
  }

  return {calendarDate, updateDate, updateMonth}
}